(function(){
    window.entitiesParamsEditors={};
    window.initScene=function(){
        initSceneEditView({});
    }

    function initSceneEditView(data){
        $("#edit-contain").html(template("addScene",data));
        rendingPageHandler();
        $("#saveGroupButton").bind("click",function(){
            selectRequestEntity();
        });
        $("#saveSceneButton").bind("click",function(){
            saveScene();
        });
        $("#invokeScene").bind("click",function(){
            invokeScene();
        });
    }

    function bindEntityCardSlide(){
        $(".entityCardSlide").unbind("click");
        $(".entityCardSlide").bind("click",function(){
            var me = $(this);
            var row = me.parents(".row:first");
            if(me.hasClass("glyphicon-chevron-down")){
                me.removeClass("glyphicon-chevron-down");
                me.addClass("glyphicon-chevron-up");
                me.attr("title","收起");
                row.find("span:first").hide();
                row.next().slideDown();
            }else{
                me.addClass("glyphicon-chevron-down");
                me.removeClass("glyphicon-chevron-up")
                row.find("span:first").show();
                me.attr("title","展开");
                row.next().slideUp();
            }
        });
    }
    window.editScene=function(target){
       var id=target.parents(".sceneBar").attr("data");
       var scene = smtPost.getSceneDetails(id);
       initSceneEditView(scene);
       for(var i=0;i<scene.requestSequence.length;i++){
           var req = scene.requestSequence[i];
           var entity = smtPost.getRequestEntity(req.entityId);
           entity.params=req.paramTpl;
           rendingRequestEntity(entity);
       }
        bindEntityCardSlide();
        rendingPageHandler();
        $(".entityCardSlide").click();
    }
    window.deleteScene=function(target){
        var confirmDialog = new dialog({
            title:"确认是否删除",
            content:"确认删除该场景吗？",
            isConfirm:true,
            onOk:function(){
                confirmDialog.close();
                var id=target.parents(".sceneBar").attr("data");
                smtPost.deleteScene(id);
            }
        })
        confirmDialog.open();
    }
    window.copyScene=function(target){
        var id=target.parents(".sceneBar").attr("data");
        var originScene = smtPost.getSceneDetails(id);
        var newScene={};
        newScene.requestSequence=originScene.requestSequence;
        newScene.name=originScene.name+"copy";
        smtPost.saveScene(newScene);
    }



    function saveScene(){
        var scene=loadScene();
        if(!scene.sceneId){
            scene.sceneId=Math.uuid();
        }
        $("#addSceneContainer input[name='sceneId']").val(scene.sceneId);
        smtPost.saveScene(scene);
    }

    function invokeScene(){
        var scene = loadScene();
        var requestSequence = scene.requestSequence;
        var entities = [];
        var envId = $("#envSelector input:first").val();
        for(var i=0;i<requestSequence.length;i++){
            var item = requestSequence[i];
            var entity = smtPost.getRequestEntity(item.entityId);
            entity.params=item.paramTpl;
            entity.invokeTime=1;
            entity.intervalTime=0;
            entity.envId=envId;
            entity=copyObject(entity);
            entity.entityId=Math.uuid();
            filterParams(entity);
            entities.push(entity);
        }
        batchInvokeConsoleStyleInit();
        //var resultDialog = createBatchInvokeResultView(entities);
        smtPost.batchInvoke(entities,function(data){
            batchInvokeConsoleStyleCallback(data);
        })
    }

    function loadScene(){
        var wells = $(".scene-entity");
        if(wells.length<=0){
            var errorDialog = new dialog({
                content:"请选择请求实体"
            });
            errorDialog.open();
            return ;
        }
        var validate = new validator({validateTarget:$("#addSceneContainer")});
        var result = validate.validate();
        if(!result.result){
            var errorDialog = new dialog({
                content:result.tip
            });
            errorDialog.open();
            return ;
        }
        var scene={};
        scene.sceneId=$("#addSceneContainer input[name='sceneId']").val();
        scene.name=$("#addSceneContainer input[name='name']").val();
        var requestSequence=[];
        wells.each(function(){
            var me = $(this);
            var entity={};
            entity.entityId=me.find("input[name='entityId']").val();
            var pair = me.find("div[data='pair']");

            var params;
            if(pair.length>0){
                params=[];
                pair.each(function(){
                    var param={};
                    var pairItem=$(this);
                    param[pairItem.find("input[name='key']").val()]=pairItem.find("input[name='value']").val();
                    params.push(param);
                });
                entity.paramTpl=params;
            }else if(me.find("textarea").length>0){
                var ue = entitiesParamsEditors[entity.entityId];
                entity.paramTpl=ue.getValue();
            }
            requestSequence.push(entity);
        });
        scene.requestSequence=requestSequence;
        return scene;
    }
    function selectRequestEntity(){
        var editDialog = new dialog({
            title:"添加请求实体",
            content:template("sceneAddRequestEntityTpl",{}),
            isConfirm:true,
            onOk:function(){
                if(bindSelectedRequestToScene()){
                    editDialog.close();
                }

            }
        });
        editDialog.open();
        var options = {};
        for(var pro in group){
            options[pro]=group[pro].name;
        }
        var requestEntitySelector = new selector({
            selector:$("#requestEntitySelector"),
            defaultLabel:"请选择请求实体"
        });
        var groupSelector = new selector({
            selector:$("#requestGroupSelector"),
            onChange:function(event){
                var selectedValue = event.value;

                var options={};
                if(selectedValue=='all'){
                    for(var pro in entities){
                        options[pro]=entities[pro].name;
                    }
                }else{
                    var groupEntities = smtPost.getGroupDetails(selectedValue);
                    for(var i=0;i<groupEntities.length;i++){
                        var item = groupEntities[i];
                        options[item.entityId]=item.name;
                    }
                }
                requestEntitySelector.refreshOptions(options);
                return true;
            },
            initData:options
        });
    }

    function bindSelectedRequestToScene(){
        //sceneSelectRequestEntity
        var validate = new validator({
            validateTarget:$("#sceneSelectRequestEntity")
        });
        var result = validate.validate();
        if(!result.result){
            var d = new dialog({
                content:result.tip
            })
            d.open();
            return false;
        }else{
            var entityId = $("#sceneSelectRequestEntity input[name='requestEntity']").val();
            var entity = smtPost.getRequestEntity(entityId);
            rendingRequestEntity(entity);
            bindEntityCardSlide();
            //$(".entityCardSlide").click();
        }
        return true;
    }

    function rendingRequestEntity(entity){
        var html = template("includeRequest",entity);
        var entityWrap = $(html);
        $("#includeRequestEntities").append(entityWrap);
        entityWrap.slideDown("slow")
        var textarea = entityWrap.find("textarea");
        if(textarea.length>0){
            var ue = createEditor(textarea);
            entitiesParamsEditors[entity.entityId]=ue;
        }
        $(".removeEntity").unbind("click");
        $(".removeEntity").bind("click",function(){
            var me =$(this);
            me.parents(".well").slideUp("slow",function(){
                $(this).remove();
            });
        });
    }

    function createEditor(targetObj){
        var type  =  targetObj.attr("type");
        var mode="";
        switch(type){
            case "text":{
                mode="text/plain";
                break;
            }
            case "html":{
                mode="text/html";
                break;
            }
            case "xml":{
                mode="text/xml";
                break;
            }
            case "json":{
                mode="application/json";
                break;
            }
        }
        var ue= CodeMirror.fromTextArea(targetObj.get(0), {
            lineNumbers: true,
            matchBrackets: true,
            autofocus:true,
            mode:mode
        });
        ue.setOption("theme", "eclipse");
        return ue;
    }
})();